package com.fbty.mt.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fbty.base.dao.MtJdbcDao;
import com.fbty.base.domain.Page;
import com.fbty.mt.dao.IpItemDao;
import com.fbty.mt.dao.ItemDao;
import com.fbty.mt.dao.OnlyIpInfoDao;
import com.fbty.mt.dao.PriceDao;
import com.fbty.mt.dao.RecordDao;
import com.fbty.mt.dao.UserDao;
import com.fbty.mt.dao.UserIpInfoDao;
import com.fbty.mt.domain.AccountInfo;
import com.fbty.mt.domain.CheckInfo;
import com.fbty.mt.domain.IpItem;
import com.fbty.mt.domain.Item;
import com.fbty.mt.domain.OnlyIpInfo;
import com.fbty.mt.domain.Price;
import com.fbty.mt.domain.Record;
import com.fbty.mt.domain.User;
import com.fbty.mt.domain.UserIpInfo;
import com.fbty.mt.service.ItemService;
import com.fbty.mt.service.ProxyService;
import com.fbty.mt.utils.DateTool;
import com.fbty.mt.utils.OnlyCodeUtil;
import com.fbty.mt.utils.OrderUtil;
import com.fbty.mt.utils.StaticValue;

public class ItemServiceImpl implements ItemService {
	private ItemDao itemDao;
	
	private MtJdbcDao mtJdbcDao;
	
	private RecordDao recordDao;
	
	private PriceDao priceDao;
	
	private UserDao userDao;
	
	private UserIpInfoDao userIpInfoDao;
	
	private OnlyIpInfoDao onlyIpInfoDao;
	
	private IpItemDao ipItemDao;
	
	private ProxyService proxyService;
	@Override
	public int saveItem(int uid, int pid,double price,int days,boolean flag) {
		Item item = new Item();
		item.setUid(uid);
		item.setPrice(price);
		item.setPid(pid);
		item.setPaystate(0);
		item.setBuyTime(System.currentTimeMillis());
		item.setDays(days);
		item.setItemNo(OrderUtil.getOrderId(uid));
		if(flag){
			item.setOnly(1);
		}else{
			item.setOnly(0);
		}
		return (Integer) itemDao.create(item);
	}
	
	@Override
	public int saveItem(Item item) {
		return (Integer) itemDao.create(item);
	}

	public ItemDao getItemDao() {
		return itemDao;
	}

	public void setItemDao(ItemDao itemDao) {
		this.itemDao = itemDao;
	}

	@Override
	public Item finItemById(int id) {
		
		return itemDao.get(id);
	}

	@Override
	public void deleteItem(int id) {
		Item item = itemDao.get(id);
		item.setState(0);
		itemDao.update(item);
	}

	@Override
	public Page queryItems(int pageNo, int pageSize,Integer flag,int uid) {
		//String hql = "from Item i where i.uid = ? and i.paystate = ? order by id desc";
		Map<String, String> sortMap = new HashMap<String, String>();
		Map<String, String> filterMap = new HashMap<String, String>();
		sortMap.put("id", "desc");
		filterMap.put("uid", uid+"");
		filterMap.put("state", 1+"");
		
		return itemDao.pagedQuery(filterMap, null, sortMap, pageNo, pageSize);
	}

	@Override
	public Page queryItems(int pageNo, int pageSize, Integer flag) {
		String sql =" SELECT i.id,i.itemNo,i.price,i.paystate,i.buyTime,u.username"+
					" FROM tab_item i,tab_user u"+
					" WHERE i.uid=u.id order by id desc";
		
		return mtJdbcDao.getMysqlJdbcTemplate().queryPageMap(sql, pageNo, pageSize);
	}

	public void setMtJdbcDao(MtJdbcDao mtJdbcDao) {
		this.mtJdbcDao = mtJdbcDao;
	}

	@Override
	public void updateItem(Item item) {
		itemDao.update(item);
	}

	@Override
	public void updateSure(int itemId,final int uId,HttpSession session) {
		final Item i = itemDao.get(itemId);
		/*
		 * 加入支付宝时候需要修改的地方和调用接口时候开户需要改的地方
		 */
		i.setPaystate(1);
		if(i.getOnly()==1){
			
			final List<Map<String, Object>> ipitems = queryList(i.getItemNo());
			
			for(final Map<String, Object> item:ipitems){
				new Thread(){
					public void run(){
						UserIpInfo uip = new UserIpInfo();
						uip.setIpid(Integer.parseInt(item.get("id").toString()));
						uip.setIptype(1);
						uip.setFlag(false);
						uip.setUid(uId);
						double days = Double.parseDouble(item.get("days").toString());
						
						uip.setEndTime(System.currentTimeMillis() + (long)(days*24*60*60*1000));
						uip.setUsername(OnlyCodeUtil.randomUsername());
						uip.setPassword(OnlyCodeUtil.randomPassword());
						uip.setAutoChange(false);
						uip.setNum(0);
						
						OnlyIpInfo onlyIpInfo = onlyIpInfoDao.get(Integer.parseInt(item.get("id").toString()));
						
						//获取IP
						String onlyIp = item.get("only_ip").toString();
						//获取端口
						int exportPort = Integer.parseInt(item.get("exportPort").toString());
								
						AccountInfo aif = proxyService.creatAccount(uip.getUsername(), uip.getPassword(), 
								DateTool.parseDateToString(new Date(uip.getEndTime()), "yyyy-MM-dd"),
								DateTool.parseDateToString(new Date(uip.getEndTime()), "HH:mm:ss"),
								onlyIp, exportPort);
						
						onlyIpInfo.setEntranceIp(aif.getHost());
						onlyIpInfo.setEntrancePort(aif.getPort());
						onlyIpInfo.setUsername(aif.getUser());
						onlyIpInfo.setPassword(aif.getPassword());
						onlyIpInfo.setState(1);//修改为已经购买
							//获取延迟
							/*CheckInfo ci = proxyService.checkConnection(onlyIpInfo.getEntranceIp(), onlyIpInfo.getEntrancePort(),
								onlyIpInfo.getUsername(), onlyIpInfo.getPassword());
						if(ci.getReslut()==CheckInfo.PROXY_CHECK_SUCCESS){
							onlyIpInfo.setSpeed(ci.getDelay()/1000+"");
						}*/
							
							
						//开户不成功
						if(aif.getResult() != 1){
							onlyIpInfo.setUsed(2);
						}	
						onlyIpInfoDao.update(onlyIpInfo);
						userIpInfoDao.save(uip);
					}
				}.start();
			}
		}else{
			Record r = new Record();
			r.setPid(i.getPid());
			r.setUid(uId);
			r.setBuyDate(new Date());
			r.setState(1);
			r.setNum(0);
			Price p =  priceDao.get(i.getPid());
			User u = userDao.get(uId);
			if(p.getType()==StaticValue.GENERAL){
				u.setNum(u.getNum()+p.getNum());
				userDao.update(u);
				session.setAttribute("num", u.getNum());
			}else if(p.getType()==StaticValue.MONTH){
				u.setMonthnum(u.getMonthnum()+p.getNum());
				session.setAttribute("monthNum", u.getMonthnum());
				userDao.update(u);
			}
			recordDao.save(r);
			
		}
		
		itemDao.update(i);
	}
	
	@Override
	public void doChangeItem(int itemId) {
		Item i = itemDao.get(itemId);
		//将订单状态置为失效
		i.setPaystate(-1);
		itemDao.update(i);
		String itemNo = i.getItemNo();
		//将订单对应的独享IP改为未使用
		String sql = "UPDATE tab_only_ip_info t SET t.state = 0 WHERE t.exportIp IN(SELECT only_ip FROM tab_ip_item WHERE item_no=?)";
		mtJdbcDao.getMysqlJdbcTemplate().update(sql, itemNo);
		
	}
	
	public void updateSure(int itemId,HttpSession session){
		Item i = itemDao.get(itemId);
		updateSure(i.getId(),i.getUid(),session);
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setRecordDao(RecordDao recordDao) {
		this.recordDao = recordDao;
	}

	public void setPriceDao(PriceDao priceDao) {
		this.priceDao = priceDao;
	}

	public void setUserIpInfoDao(UserIpInfoDao userIpInfoDao) {
		this.userIpInfoDao = userIpInfoDao;
	}

	public void setOnlyIpInfoDao(OnlyIpInfoDao onlyIpInfoDao) {
		this.onlyIpInfoDao = onlyIpInfoDao;
	}

	public void setProxyService(ProxyService proxyService) {
		this.proxyService = proxyService;
	}
	
	public List<Map<String, Object>> queryList(String itemNo){
		
		String sql = "SELECT toi.id,ti.days,ti.only_ip,toi.exportPort FROM tab_ip_item ti,tab_only_ip_info toi WHERE ti.only_ip = toi.exportIp and ti.item_no=?";
		
		List<Map<String, Object>> list =  mtJdbcDao.getMysqlJdbcTemplate().queryForList(sql, itemNo);
		return list;
	}

	@Override
	public Item findByNo(String itemNo) throws Exception {
		String hql = "from Item where itemNo=? and state=1";
		List<Item> list = itemDao.find(hql, new Object[]{itemNo});
		if(list.size()==1){
			return list.get(0);
		}
		return null;
	}
	
	public void setIpItemDao(IpItemDao ipItemDao) {
		this.ipItemDao = ipItemDao;
	}
	
	public static void main(String[] args) {
		float d = 0.5f;
		System.out.println(d);
		System.out.println((long)d*24*60*60*1000);
	}
}
